package com.booklove.service.order;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.booklove.constant.OrderTypeConstant;
import com.booklove.domain.dto.PageDTO;
import com.booklove.domain.po.Orders;
import com.booklove.domain.query.OrdersQuery;
import com.booklove.domain.vo.DonatebookVO;
import com.booklove.domain.vo.OrdersVO;
import com.booklove.domain.vo.WishbookVO;
import com.booklove.mapper.DonatebookMapper;
import com.booklove.mapper.OrdersMapper;
import com.booklove.mapper.WishbookMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 订单列表 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-09-24
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private DonatebookMapper donatebookMapper;
    @Autowired
    private WishbookMapper wishbookMapper;

    @Override
    public OrdersVO getByVOId(Integer id) {
        Orders orders = baseMapper.selectById(id);

        OrdersVO ordersVO = new OrdersVO();
        BeanUtils.copyProperties(orders, ordersVO);

        if (orders.getOrderType() == OrderTypeConstant.IS_DONATE) {
            WishbookVO wishbookVO = wishbookMapper.getVOById(orders.getWishBookId());
            ordersVO.setBookName(wishbookVO.getBookName());
            ordersVO.setTitle(wishbookVO.getTitle());
            ordersVO.setUserShopId(wishbookVO.getUserId());
        } else if (orders.getOrderType() == OrderTypeConstant.IS_TAKE) {
            DonatebookVO donatebookVO = donatebookMapper.getVOById(orders.getDonateBookId());
            ordersVO.setBookName(donatebookVO.getName());
            ordersVO.setTitle(donatebookVO.getTitle());
            ordersVO.setUserShopId(donatebookVO.getUserId());

        }

        return ordersVO;
    }

    @Override
    public PageDTO<OrdersVO> queryOrderssPage(OrdersQuery ordersQuery) {
        // 1.添加排序规则
        // 使用内置的函数转换并且 设置规则
        List<OrderItem> orderItems = ordersQuery.toMpOrderItems();

        // 获取分页对象和排序情况
        Page<OrdersVO> page = ordersQuery.toMpPageDefaultSortByIdAsc(orderItems.toArray(new OrderItem[0]));
        /*
        查询
         */
        Page<OrdersVO> p = new Page<OrdersVO>();
        if (ordersQuery.getOrderType() == OrderTypeConstant.IS_DONATE) {
            p = baseMapper.selectIsWishOrderPageVO(page, ordersQuery);
        } else if (ordersQuery.getOrderType() == OrderTypeConstant.IS_TAKE) {
            p = baseMapper.selectIsDonateOrderPageVO(page, ordersQuery);

        }

        // 获取数据信息
        return PageDTO.of(p, OrdersVO.class);
    }
}
